package com.mchat.wsserver;

import com.mchat.friend.domain.vo.FriendRequestVO;
import com.mchat.proto.FriendRequest;
import com.mchat.proto.PushOffline;
import com.mchat.wsserver.enums.ClientOperation;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

import java.time.LocalDateTime;

import static com.mchat.util.Utils.toProtoTimestamp;

public class MessageUtil {
    //池化的直接内存申请器
    private static final PooledByteBufAllocator ALLOC = PooledByteBufAllocator.DEFAULT;
    public static BinaryWebSocketFrame sendOfflineMessage(String title,String reason){
        PushOffline proto = PushOffline.newBuilder()
                .setDate(toProtoTimestamp(LocalDateTime.now()))
                .setTitle(title)
                .setReason(reason)
                .build();
        ByteBuf buffer = ALLOC.directBuffer(10+proto.getSerializedSize());
        //version
        buffer.writeByte(0);
        //opcode
        buffer.writeInt(ClientOperation.PUSH_OFFLINE);
        //seq
        buffer.writeInt(0);
        //isEnd
        buffer.writeByte(1);
        buffer.writeBytes(proto.toByteArray());
        return new BinaryWebSocketFrame(buffer);
    }
    public static BinaryWebSocketFrame sendFriendApply(FriendRequestVO vo){
        FriendRequest proto = FriendRequest.newBuilder()
                .setId(vo.getId())
                .setSendId(vo.getSendId())
                .setReceiverId(vo.getReceiverId())
                .setMsg(vo.getMsg())
                .setStatus(vo.getStatus())
                .setDate(toProtoTimestamp(vo.getCreateTime()))
                .build();
        ByteBuf buffer = ALLOC.directBuffer(10+proto.getSerializedSize());
        //version
        buffer.writeByte(0);
        //opcode
        buffer.writeInt(ClientOperation.FRIEND_APPLY);
        //seq
        buffer.writeInt(0);
        //isEnd
        buffer.writeByte(1);
        buffer.writeBytes(proto.toByteArray());

       return  new BinaryWebSocketFrame(buffer);

    }
}
